<template>
  <basic-container>
    <el-row style="margin-bottom: 20px">
      <el-tabs type="border-card" class="informationLabel">
        <el-tab-pane label="供应商来料质量统计搜索">
          <avue-form ref="form" :option="searchOption" v-model="form" @reset-change="handleCancel" @submit="handleSubmit"></avue-form>
        </el-tab-pane>
      </el-tabs>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-tabs type="border-card" class="informationLabel">
          <el-tab-pane label="供应商来料质量统计明细">
            <div class="chart-header">
              <el-dropdown @command="handleExport">
                <el-button type="warning" size="small">导出<i class="el-icon-download"></i> </el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="pdf">导出pdf</el-dropdown-item>
                  <el-dropdown-item command="excel">导出excel</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
            <!-- <div style="width: 100%"> -->
            <chart-view v-if="isShowChartOptionOne" class="chart-content" :chart-option="chartOptionOne" :auto-resize="true" width="100%" />
            <avue-crud :option="option" :table-loading="loading" :data="data" :page.sync="page" @current-change="currentChange" @size-change="sizeChange" ref="crud">
              <template #passRateHeader="{ column }">
                {{ (column || {}).label }}
                <el-tooltip class="item" effect="dark" content="供应商来料批合格率，计算公式为(合格批次/总检查批次) * 100%" placement="top">
                  <span><i class="el-icon-info"></i></span>
                </el-tooltip>
              </template>
              <template slot="menuRight" v-if="searchTime">
                <div class="search-time">
                  <span> 当前查询时间:{{ searchTime }} </span>
                </div>
              </template>
              <template slot="menu" slot-scope="scope">
                <el-button type="text" size="small" icon="el-icon-view" @click="handleDetail(scope.row)">详情</el-button>
                <el-button type="text" size="small" icon="el-icon-s-data" @click="handleEchart(scope.row)">趋势图</el-button>
              </template>
            </avue-crud>
            <!-- </div> -->
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
    <export-comp
      ref="exportComp"
      page-api-url="mes-product/qms-inspection-document-report/pass-rate/page"
      :option="option"
      :page="page"
      :query="exprotParams"
      file-name="供应商来料质量统计报表"
    >
    </export-comp>
    <export-pdf
      ref="exportPdf"
      url="/api/mes-product/qms-inspection-document-report/pass-rate/page"
      name="供应商来料质量统计报表"
      :option="option"
      :chartOption="chartOptionOne"
      :page="page"
      :query="exprotParams"
      :pdfConfig="pdfConfig"
    ></export-pdf>
    <el-dialog title="查询进度" :visible.sync="dialogVisible" width="30%" append-to-body>
      <el-progress :percentage="currentProgress" stroke-width="40" stroke-linecap="square" :show-text="false"></el-progress>
    </el-dialog>
    <el-dialog class="detailDialog" title="详情" append-to-body :visible.sync="detailDialog" width="60%" @close="closeImportDialog">
      <div style="font-size: 18px">
        <span>供应商名称：{{ vendorName }}</span
        >&nbsp;&nbsp;&nbsp;&nbsp;
        <span>供应商编码：{{ vendorCode }}</span>
      </div>
      <avue-crud :option="detailOption" :data="detailData" @refresh-change="refreshChange">
        <template slot="menu" slot-scope="scope">
          <el-button type="text" size="small" icon="el-icon-view" @click="viewInspectionDetail(scope.row)">详情</el-button>
        </template>
      </avue-crud>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" icon="el-icon-circle-close" @click="detailDialog = false">取 消</el-button>
      </span>
    </el-dialog>
    <el-dialog title="趋势图" append-to-body :visible.sync="echartDialog" width="60%" @close="closeImportDialog">
      <div style="display: flex; justify-content: space-between; font-size: 18px">
        <div>
          <span>供应商名称：{{ vendorName }}</span
          >&nbsp;&nbsp;&nbsp;&nbsp;
          <span>供应商编码：{{ vendorCode }}</span>
        </div>
        <div>图为该供应商近一年内LAR值趋势图</div>
      </div>
      <chart-view class="chart-content" :chart-option="chartOptionTwo" :auto-resize="true" width="100%" />
    </el-dialog>
    <iqc-inspection-record-detail ref="detailForm" :visible.sync="inspectionDetailDialog"></iqc-inspection-record-detail>
    <common-modal-template ref="commonModalTemplate" :option="selectOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"></common-modal-template>
  </basic-container>
</template>

<script>
import ChartView from '@/components/chart/index.vue';
import moment from 'moment';
import { getList, getDetail, getEchart } from '@/api/report/supplierIncomingMaterialQualityStatistics';
import exportComp from '@/components/export-comp';
import commonModalTemplate from '@/components/common-modal-template/common-modal-template';
import iqcInspectionRecordDetail from '@/views/quality/refactor/iqc-inspection-record-detail';
import exportPdf from '@/components/export-pdf/index.vue';
export default {
  name: 'supplierIncomingMaterialQualityStatistics',
  components: {
    ChartView,
    exportComp,
    commonModalTemplate,
    iqcInspectionRecordDetail,
    exportPdf
  },
  data() {
    return {
      dialogVisible: false,
      currentProgress: 0,
      modalName: '',
      timer: new Date().getTime(),
      search: {},
      searchTime: '',
      params: {},
      form: {},
      searchOption: {
        submitBtn: true,
        submitText: '搜索',
        emptyBtn: true,
        emptyText: '清空',
        menuPosition: 'right',
        menuSpan: 6,
        column: [
          {
            label: '时间范围',
            span: 6,
            prop: 'month',
            type: 'monthrange',
            format: 'yyyy-MM',
            startPlaceholder: '开始月份',
            endPlaceholder: '结束月份',
            valueFormat: 'yyyy-MM',
            display: true,
            pickerOptions: {
              disabledDate(time) {
                return time.getTime() > Date.now();
              }
            },
            rules: [
              {
                required: true,
                message: '请选择时间范围',
                trigger: 'blur'
              },
              { validator: this.validateDateRange, trigger: 'change' }
            ]
          },
          {
            label: '供应商名称',
            span: 6,
            prop: 'partnerName'
          },
          {
            label: '供应商编码',
            span: 6,
            prop: 'code'
          }
        ]
      },
      isShowChartOptionOne: false,
      pdfConfig: { unit: 'pt', format: 'c4', orientation: 'portrait' },
      chartOptionOne: {
        title: {
          text: '供应商来料质量统计报表',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          top: '10%',
          data: ['总检批次', '合格批次', '目标值', 'LAR值']
        },
        color: ['#4874cb', '#ee822f', '#f2ba02', '#78be47'],
        grid: {
          left: '3%',
          right: '4%',
          bottom: '9%'
        },
        xAxis: {
          type: 'category',
          data: []
        },
        yAxis: [
          {
            type: 'value',
            alignTicks: true
          },
          {
            type: 'value',
            alignTicks: true,
            axisLabel: {
              formatter: '{value} %'
            }
          }
        ],
        series: [
          {
            name: '总检批次',
            type: 'bar',
            data: []
          },
          {
            name: '合格批次',
            type: 'bar',
            data: []
          },
          {
            name: '目标值',
            type: 'line',
            data: [],
            yAxisIndex: 1,
            tooltip: {
              valueFormatter: function (value) {
                return value + ' %';
              }
            }
          },
          {
            name: 'LAR值',
            yAxisIndex: 1,
            type: 'line',
            data: [],
            yAxisIndex: 1,
            tooltip: {
              valueFormatter: function (value) {
                return value + ' %';
              }
            }
          }
        ]
      },
      loading: false,
      data: [],
      option: {
        height: 'calc(100vh - 576px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 3,
        border: true,
        index: true,
        indexLabel: '序号',
        selection: true,
        dialogClickModal: false,
        labelWidth: 120,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        viewBtn: false,
        menu: true,
        column: [
          {
            label: '日期',
            prop: 'date'
          },
          {
            label: '供应商名称',
            prop: 'partnerName'
          },
          {
            label: '供应商编码',
            prop: 'code'
          },
          {
            label: '总检批次数',
            prop: 'examineTotalTimes'
          },
          {
            label: '合格批次数',
            prop: 'examineOkTimes'
          },
          {
            label: '不合格批次数',
            prop: 'examineNgTimes'
          },
          {
            label: '目标值',
            prop: 'targetValue',
            formatter: (val, value, label) => {
              return value && value != null ? `${value}%` : '';
            }
          },
          {
            label: 'LAR值',
            prop: 'passRate',
            formatter: (val, value, label) => {
              return value && value != null ? `${value}%` : '';
            }
          },
          {
            label: '达成情况',
            prop: 'achievementStatus',
            html: true,
            formatter: (val) => {
              if (val.achievementStatus === 'OK') {
                return '<b style="color:#9af30f">' + val.achievementStatus + '</b>';
              } else if (val.achievementStatus === 'NG') {
                return '<b style="color:red">' + val.achievementStatus + '</b>';
              }
            }
          }
        ]
      },
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      detailDialog: false,
      detailOption: {
        height: 500,
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        indexLabel: '序号',
        selection: false,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        viewBtn: false,
        menu: true,
        menuWidth: 100,
        refreshBtn: false,
        columnBtn: false,
        column: [
          {
            label: '收料时间',
            prop: 'receivingTime',
            type: 'datetime',
            format: 'yyyy-MM-DD HH:mm:ss'
          },
          {
            label: '收料数量',
            prop: 'receivingQuantity'
          },
          {
            label: '检验单号',
            prop: 'documentNo'
          },
          {
            label: '物料编码',
            prop: 'partNo'
          },
          {
            label: '物料名称',
            prop: 'partName'
          },
          {
            label: '物料规格',
            prop: 'partModel'
          },
          {
            label: '检验方式',
            prop: 'examineMode',
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=inspection_mode',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          },
          {
            label: '检验结果',
            prop: 'examineResult'
          }
        ]
      },
      vendorName: '',
      vendorCode: '',
      detailData: [],
      inspectionDetailDialog: false,
      echartDialog: false,
      chartOptionTwo: {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          top: '10%',
          tooltip: {
            show: true
          }
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: [],
          name: '日期'
        },
        yAxis: {
          name: 'LAR值',
          alignTicks: true,
          type: 'value',
          axisLabel: {
            formatter: '{value} %'
          }
        },
        series: []
      },
      exprotParams: {}
    };
  },
  mounted() {
    setTimeout(() => {
      this.isShowChartOptionOne = true;
    }, 500);
  },
  computed: {},
  methods: {
    newKey() {
      this.timer = new Date().getTime();
    },
    onLoad(page) {
      let params = this.getParams();
      let startTime = new Date().getTime();
      let endTime;
      getList(page.currentPage, page.pageSize, params).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        endTime = new Date().getTime();
        const seconds = endTime - startTime;
        this.startProgress(data.records, seconds);
        let xAxisList = [];
        let examineTotalTimesList = [];
        let examineOkTimesList = [];
        let targetValueList = [];
        let passRateList = [];
        this._forEach(data.records, (item) => {
          xAxisList.push(`${item.date}+${item.partnerName}`);
          examineTotalTimesList.push(item.examineTotalTimes && item.examineTotalTimes != null ? item.examineTotalTimes : 0);
          examineOkTimesList.push(item.examineOkTimes && item.examineOkTimes != null ? item.examineOkTimes : 0);
          targetValueList.push(item.targetValue && item.targetValue != null ? item.targetValue : 0);
          passRateList.push(item.passRate && item.passRate != null ? item.passRate : 0);
        });
        let series = [
          {
            name: '总检批次',
            type: 'bar',
            data: examineTotalTimesList
          },
          {
            name: '合格批次',
            type: 'bar',
            data: examineOkTimesList
          },
          {
            name: '目标值',
            type: 'line',
            data: targetValueList,
            yAxisIndex: 1,
            tooltip: {
              valueFormatter: function (value) {
                return value && value != null ? value + ' %' : '';
              }
            }
          },
          {
            name: 'LAR值',
            yAxisIndex: 1,
            type: 'line',
            data: passRateList,
            yAxisIndex: 1,
            tooltip: {
              valueFormatter: function (value) {
                return value && value != null ? value + ' %' : '';
              }
            }
          }
        ];
        const xAxis = {
          type: 'category',
          data: xAxisList,
          axisLabel: {
            formatter: function (value) {
              let partnerName = value ? value.split('+')[0] : '';
              let date = value ? value.split('+')[1] : '';
              return `${date}\n${partnerName}`;
            }
          },
          axisTick: {
            alignWithLabel: false
          }
        };
        this.$set(this.chartOptionOne, 'xAxis', xAxis);
        this.$set(this.chartOptionOne, 'series', series);
      });
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.onLoad(this.page);
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.onLoad(this.page);
    },
    handleSubmit(form, done) {
      this.page.currentPage = 1;
      this.$refs.form.validate((valid, done) => {
        if (valid) {
          this.dialogVisible = true;
          this.onLoad(this.page);
        }
        done();
      });
    },
    startProgress(data, seconds = 500) {
      const time = seconds < 500 ? 500 : seconds;
      const setInterTime = time / 10;
      this.intervalId = setInterval(() => {
        if (this.currentProgress < 100) {
          this.currentProgress += 10;
        } else {
          clearInterval(this.intervalId);
          this.dialogVisible = false;
          this.data = data;
        }
      }, setInterTime);
    },
    handleCancel() {
      this.form = {
        month: [],
        partnerName: '',
        partnerNo: ''
      };
      this.data = [];
      this.page.total = 0;
      // this.$refs.form.resetForm();
      let xAxis = {
        type: 'category',
        data: []
      };
      let series = [
        {
          name: '总检批次',
          type: 'bar',
          data: []
        },
        {
          name: '合格批次',
          type: 'bar',
          data: []
        },
        {
          name: '目标值',
          type: 'line',
          data: [],
          yAxisIndex: 1,
          tooltip: {
            valueFormatter: function (value) {
              return value + ' %';
            }
          }
        },
        {
          name: 'LAR值',
          yAxisIndex: 1,
          type: 'line',
          data: [],
          yAxisIndex: 1,
          tooltip: {
            valueFormatter: function (value) {
              return value + ' %';
            }
          }
        }
      ];
      this.$set(this.chartOptionOne, 'xAxis', xAxis);
      this.$set(this.chartOptionOne, 'series', series);
    },
    validateDateRange(rule, value, callback) {
      if (!this.form.month.length) {
        callback(new Error('请选择时间范围'));
      }
      // 假设有两个时间对象：startTime 和 endTime
      const startTime = moment(this.form.month[0], 'YYYY-MM');
      const endTime = moment(this.form.month[1], 'YYYY-MM');

      // 计算两个时间之间的月份差
      const monthDiff = endTime.diff(startTime, 'months');

      if (monthDiff <= 12) {
        callback();
      } else {
        // 月份差大于 12，超出范围
        callback(new Error('月范围不能超过 12 个月'));
      }
    },
    handleDetail(row) {
      this.vendorName = row.partnerName;
      this.vendorCode = row.partnerNo;
      this.detailDialog = true;
      let params = {
        partnerId: row.partnerId
      };
      params.startTime = this.$moment(row.date).format('YYYY-MM');
      params.endTime = this.$moment(row.date).format('YYYY-MM');
      getDetail(params).then(
        (res) => {
          this.detailData = this._get(res, 'data.data', []);
        },
        (error) => {
          this.detailData = [];
        }
      );
    },
    async viewInspectionDetail(row) {
      await this.$refs.detailForm.iqcExamine({ id: row.documentId });
      this.inspectionDetailDialog = true;
    },
    handleExport(val) {
      this.$refs.form.validate((valid, done) => {
        if (valid) {
          this.exprotParams = this.getParams();
          if (val === 'excel') {
            this.$refs.exportComp.visible = true;
            done();
          } else {
            this.$refs.exportPdf.openDialog();
            done();
          }
        }
      });
    },
    getParams() {
      let params = {
        documentType: 'IQC',
        partnerName: this.form.partnerName,
        partnerNo: this.form.partnerNo
      };
      params.startTime = this.$moment(this.form.month[0]).format('YYYY-MM');
      params.endTime = this.$moment(this.form.month[1]).format('YYYY-MM');
      return params;
    },
    handleEchart(row) {
      this.vendorName = row.partnerName;
      this.vendorCode = row.partnerNo;
      this.echartDialog = true;
      let params = {
        partnerId: row.partnerId,
        documentType: 'IQC'
      };
      getEchart(params).then(
        (res) => {
          let data = this._get(res, 'data.data', []);
          let xAxisList = [];
          let passRateList = [];
          this._forEach(data, (item) => {
            xAxisList.push(item.date);
            passRateList.push(item.passRate && item.passRate != null ? item.passRate : 0);
          });
          let xAxisData = xAxisList;
          let yaxisData = passRateList;
          let series = [
            {
              type: 'line',
              data: yaxisData.reverse(),
              tooltip: {
                valueFormatter: function (value) {
                  return value ? value + ' %' : '';
                }
              }
            }
          ];
          const xAxis = {
            type: 'category',
            boundaryGap: false,
            data: xAxisData.reverse()
          };
          this.$set(this.chartOptionTwo, 'xAxis', xAxis);
          this.$set(this.chartOptionTwo, 'series', series);
        },
        (error) => {
          this.$set(this.chartOptionTwo, 'xAxis', []);
          this.$set(this.chartOptionTwo, 'series', []);
        }
      );
    }
  }
};
</script>

<style scoped lang="scss">
.page-contianer {
  height: calc(100vh - 160px);
}
.main-content {
  height: 650px;
  overflow-y: scroll;
  overflow-x: hidden;
}
.chart-header {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 10px;
  height: 40px;

  .workshopSelect {
    position: absolute;
    left: 100px;
  }

  .opration-div {
    position: absolute;
    left: 50px;
    font-size: 14px;
    color: #606266;
  }
}
.search-time {
  font-size: 14px;
  color: #606266;
  height: 40px;
  display: flex;
  flex-direction: column;
  flex-wrap: nowrap;
  justify-content: flex-end;
  span {
    display: inline-block;
  }
}
.tab-font {
  ::v-deep .el-tabs__item {
    color: #606266 !important;
    font-weight: bold;
  }
}
.invalid-input {
  position: relative;
  ::v-deep .el-input__inner {
    border: 1px solid #f56c6c;
  }
}
.invalid-span {
  color: #f56c6c;
  font-size: 12px;
  line-height: 1;
  padding-top: 4px;
  position: relative;
  top: -7px;
}
.detailDialog {
  ::v-deep .avue-crud__menu {
    display: none;
  }
}
.chart-header {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-bottom: 10px;
}
</style>
